$(document).ready(function(){
    user.layerDate();//调用时间插件
    user.loaduserListTable();//加载数据表格
    user.searchTurn();//点击查询
    user.turnType();//调用工具类型接口
    user.statInfo();//统计按钮
    /*统计条件下拉框点击选项阻止收起事件*/
    $(".dropdown-menu").on("click","[data-stopPropagation]",function(e){
        e.stopPropagation();
    })
    var btnElement = '#SearchForm .dis, #userUseBtn .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限
});

var user = {};
(function(res){
    //调用时间插件
    res.layerDate = function(){
        laydate.skin('molv');/* 设置时间插件的皮肤 */
        var startTime = {
            elem: '#startTime', //选择ID为START的input
            format: 'YYYY-MM-DD', //自动生成的时间格式
            max: laydate.now(), //最大日期
            istoday: false,  //是否是当天
            start: laydate.now(0,"YYYY-MM-DD"),  //设置开始时间为当前时间
        };
        var endTime = {
            elem: '#endTime', //选择ID为START的input
            format: 'YYYY-MM-DD',
            max: laydate.now(), //最大日期
            istoday: false,  //是否是当天
            start: laydate.now(0,"YYYY-MM-DD"),  //设置开始时间为当前时间
        };
        laydate(startTime);
        laydate(endTime);
    }
    res.loaduserListTable = function(url){
        $('#userListTable').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
        var time = new Date();
        var timeDate = new Date(time).Format("hh:mm:ss");  //获取当前系统时间
        var type = $("#typeTurn").val();
        var toolName = $("#toolNameTurn").val();
        var status = $("#statusTurn").val();
        var base = $("#baseTurn").val();
        var numberTurn = $("#noTurns").val();
        var startTime = ($("#startTime").val()==null||$("#startTime").val()=="")?"":$("#startTime").val()+" 00:00:00";
        var endTime = ($("#endTime").val()==null||$("#endTime").val()=="")?"":$("#endTime").val()+" "+timeDate;
        /*获取显示表头数据参数并去null和undefined*/
        var basem  = $('#userInventory input[name="basem"]:checked').val();
        var typem  = $('#userInventory input[name="typem"]:checked').val();
        var toolNamem  = $('#userInventory input[name="toolNamem"]:checked').val();
        var nom  = $('#userInventory input[name="nom"]:checked').val();
        var areaNamem  = $('#userInventory input[name="areaNamem"]:checked').val();
        var statusm  = $('#userInventory input[name="statusm"]:checked').val();
        var ToolSum  = $('#userInventory input[name="ToolSum"]:checked').val();
        var areaName = $('#userInventory input[name="areaName"]:checked').val();
        var longitudem =$('#userInventory input[name="longitudem"]:checked').val();
        var latitudem = $('#userInventory input[name="latitudem"]:checked').val();
        var trajectoryChangeTimem =  $('#userInventory input[name="trajectoryChangeTimem"]:checked').val();
        /*初始化表格*/
        $('#userListTable').bootstrapTable({
            method: 'POST',
            url:'../toolController/getToolStatistical',   /* 调用后台接口加载数据 */
            queryParamsType:'',
            queryParams:function (params) {
                var pageSize = params.pageSize;
                var pageNum = params.pageNumber;
                return {  /*参数*/
                    pageNum:pageNum,
                    pageSize:pageSize,
                    /*条件查询参数*/
                    trajectoryChangeTime:new Date().Format("yyyy-MM-dd"),
                    type:type,
                    status:status,
                    base:base,
                    no:numberTurn,
                    toolName:toolName,
                    startTime:startTime,
                    endTime:endTime,
                    /*表格显示隐藏参数*/
                    basem:basem,
                    typem:typem,
                    toolNamem:toolNamem,
                    nom:nom,
                    areaNamem:areaNamem,
                    statusm:statusm,
                    ToolSum:ToolSum,
                    areaName:areaName,
                    longitudem:longitudem,
                    latitudem:latitudem,
                    trajectoryChangeTimem:trajectoryChangeTimem
                };
            },
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#userUseBtn',//工具列
            pageSize: 10,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
            sidePagination: "server",
            showRefresh: true,  //是否显示刷新按钮
            columns: [
                {field: 'num',title: '序号',width: 20,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
                {field:"type",title:"工具类型",align:"center",valign:"middle",sortable:"true"},
                {field:"toolName",title:"工具名称",align:"center",valign:"middle",sortable:"true"},
                {field:"no",title:"工具编号",align:"center",valign:"middle",sortable:"true"},
                {field:"areaName",title:"丢失区域",align:"center",valign:"middle",sortable:"true"},
                {field:"longitude",title:"经度",align:"center",valign:"middle",sortable:"true"},
                {field:"latitude",title:"纬度",align:"center",valign:"middle",sortable:"true"},
                {field:"trajectoryChangeTime",title:"丢失时间",align:"center",valign:"middle",sortable:"true",formatter:function(value){
                    if(value==""||value==null){
                        return "";
                    }else{
                        return res.dateFormat(new Date(value), "yyyy-MM-dd hh:mm:ss");
                    }
                }},
                {field:"status",title:"状态",align:"center",valign:"middle",sortable:"true"},
                {field:"base",title:"归属地",align:"center",valign:"middle",sortable:"true"},
                {field:"toolSum",title:"数量",align:"center",valign:"middle",sortable:"true"},
            ],
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            },
            responseHandler: function(res) {
                var total ,rows;
                if (res.data!=null&&res.data.length!=0) {
                    total = res.data[0].total;
                    rows = res.data;
                }else {
                    total = 0;
                    rows = new Array();
                }
                return {
                    "total":total,//total,//总页数
                    "rows":rows  //数据
                };
            }
        });
        //判断统计条件是否勾选，勾选则显示，未勾选则隐藏
        var obj = $("#userInventory input");
        for (var i = 0 ; i<obj.length; i++) {
            $('#userListTable').bootstrapTable('hideColumn', obj[i].value.toString());
            if(obj[i].type=="checkbox" && obj[i].checked){
                $('#userListTable').bootstrapTable('showColumn', obj[i].value.toString());
            }
        }
        res.statInfo = function(){
            var chkobj = $("#userInventory input[type='checkbox']:checked");
            if(chkobj.length < 1){
                layer.msg("至少选择一个项目统计");
                return false;
            }else{
                res.loaduserListTable();
            }
        }
        $(window).resize(function (e, value, row, index) {
            $('#userListTable').bootstrapTable('resetView');
        });
    }

    //点击搜索查询
    res.searchTurn = function () {
        $("#searchTools").click(function(){
            res.loaduserListTable();
        });
    }
    //工具类型接口
    res.turnType = function(){
        $('#turnType').selectpicker('refresh');//刷新下拉框
        $('#statusTurn').selectpicker('refresh');//刷新下拉框
        $("#baseTurn").selectpicker('refresh');//刷新下拉框
        /* 页面加载获取产品下拉框数据 */
        var tool_type = 'tool_type';
        var tool_status = 'tool_status';
        var base = 'base';
        res.selecAjax(tool_type);
        res.selecAjax(tool_status);
        res.selecAjax(base);
    }
    //调用下拉框ajax方法
    res.selecAjax = function(item){
        $.ajax({
            type: "POST",
            data:{
                parentcode:item,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt ='<option value="" selected="true">请选择</option>';
                var txt1='<option value="" selected="true">请选择</option>';
                var txt2='<option value="" selected="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(res[i].parentcode == "tool_type"){
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#typeTurn').html(txt);
                        $('#typeTurn').selectpicker('refresh');
                    }else if(res[i].parentcode == "tool_status"){
                        txt1 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#statusTurn').html(txt1);
                        $('#statusTurn').selectpicker('refresh');
                    }else if(res[i].parentcode == "base"){
                        txt2 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#baseTurn').html(txt2);
                        $('#baseTurn').selectpicker('refresh');
                    }
                }
            }
        });
    }
    //导出
    user.eaportData = function(){
        var type = $("#typeTurn").val();
        var toolName = $("#toolNameTurn").val();
        var status = $("#statusTurn").val();
        var base = $("#baseTurn").val();
        var numberTurn = $("#noTurns").val();
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        var trajectoryChangeTime =  new Date().Format("yyyy-MM-dd");

        var basem  = $('#userInventory input[name="basem"]:checked').val();
        var typem  = $('#userInventory input[name="typem"]:checked').val();
        var toolNamem  = $('#userInventory input[name="toolNamem"]:checked').val();
        var nom  = $('#userInventory input[name="nom"]:checked').val();
        var areaNamem  = $('#userInventory input[name="areaNamem"]:checked').val();
        var statusm  = $('#userInventory input[name="statusm"]:checked').val();
        var ToolSum  = $('#userInventory input[name="ToolSum"]:checked').val();
        var areaName = $('#userInventory input[name="areaName"]:checked').val();
        var longitudem =$('#userInventory input[name="longitudem"]:checked').val();
        var latitudem = $('#userInventory input[name="latitudem"]:checked').val();
        var trajectoryChangeTimem =  $('#userInventory input[name="trajectoryChangeTimem"]:checked').val();
        /*var dataTime =  new Date().Format("yyyy-MM-dd");*/
        $.ajax({
            type:"post",
            url:"../toolController/exportExcelToolStatistics ",
            data:{
                "type":type,
                "trajectoryChangeTime":trajectoryChangeTime,
                "toolName":toolName,
                "base":base,
                "status":status,
                "no":numberTurn,
                "basem":basem,
                "typem":typem,
                "toolNamem":toolNamem,
                "nom":nom,
                "startTime":startTime,
                "endTime":endTime,
                "areaNamem":areaNamem,
                "statusm":statusm,
                "ToolSum":ToolSum,
                "areaName":areaName,
                "longitudem":longitudem,
                "latitudem":latitudem,
                "trajectoryChangeTimem":trajectoryChangeTimem,
                "title":"丢失工具统计"
            },
            success:function(data){
                if(data.code== 0){
                    window.location.href = data.url;
                }
            }
        })
    }
    /*时间戳格式化*/
    res.dateFormat=function (now,mask) {
        var d = new Date(now);
        var zeroize = function (value, length)
        {
            if (!length) length = 2;
            value = String(value);
            for (var i = 0, zeros = ''; i < (length - value.length); i++)
            {
                zeros += '0';
            }
            return zeros + value;
        };

        return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
        {
            switch ($0)
            {
                case 'd': return d.getDate();
                case 'dd': return zeroize(d.getDate());
                case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
                case 'M': return d.getMonth() + 1;
                case 'MM': return zeroize(d.getMonth() + 1);
                case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
                case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
                case 'yy': return String(d.getFullYear()).substr(2);
                case 'yyyy': return d.getFullYear();
                case 'h': return d.getHours() % 12 || 12;
                case 'hh': return zeroize(d.getHours() % 12 || 12);
                case 'H': return d.getHours();
                case 'HH': return zeroize(d.getHours());
                case 'm': return d.getMinutes();
                case 'mm': return zeroize(d.getMinutes());
                case 's': return d.getSeconds();
                case 'ss': return zeroize(d.getSeconds());
                case 'l': return zeroize(d.getMilliseconds(), 3);
                case 'L': var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
                case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
                case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
                default: return $0.substr(1, $0.length - 2);
            }
        });
    }
})(user);

Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}